from google.appengine.ext import webapp, db
from google.appengine.api.datastore_errors import BadKeyError
from app.helpers.views import renders_template
from app.helpers.access import requires_permission
from app.helpers.queries import Query
from app.helpers import properties
from app.models.tags import Tag
from app.models.fieldsets import FieldSet, DEFAULT_PRIMARY_FIELDSET
import urllib

FIELD_TYPES = {}

for name in dir(properties):
  value = getattr(properties, name)
  try:
    if issubclass(value, db.Property):
      FIELD_TYPES[name] = value
  except TypeError:
    pass

class Fieldsets(webapp.RequestHandler):
  """ Lists all existing fieldsets """
  @requires_permission('fieldsets')
  @renders_template('fieldsets','templates','list.html')
  def get(self):
    default_primary = DEFAULT_PRIMARY_FIELDSET
    
    return {
      'default_primary' : default_primary,
      'fieldsets' : Query(FieldSet).filter(dataset_key=self.dataset.key())\
        .filter('__key__ != ', default_primary)
    }

class FieldsetsView(webapp.RequestHandler):
  """ Show individual fieldset """
  @requires_permission('fieldsets')
  @renders_template('fieldsets','templates','view.html')
  def get(self):
    key = self.request.get('key', '')
    try:
      fieldset = FieldSet.get(db.Key(key))
      # Check ownership
      if fieldset.dataset_key != self.dataset.key():
        raise BadKeyError()
      
      tags = Query(Tag).filter(fieldset_key=fieldset.key()).order('verbose_property').fetch(1000)
      
      return { 'fieldset' : fieldset, 'tags' : tags }
      
    except BadKeyError:
      self.response.out.write("That field set does not exist")

class FieldsetsCreate(webapp.RequestHandler):
  """ Create a new fieldset """
  @requires_permission('fieldsets')
  @renders_template('fieldsets','templates','create.html')
  def get(self):
    return {
      'field_types' : FIELD_TYPES.items()
    }
  
  @requires_permission('fieldsets')
  def post(self):
    name = self.request.get('name')
    if not name.strip():
      self.response.out.write('Field set name required.')
      return
    
    types = self.request.get_all('field_type')
    names = self.request.get_all('field_name')
    
    fields_list = []
    for field_type, field_name in zip(types, names):
      if not field_name.strip(): continue
      fields_list.append(FIELD_TYPES[field_type](verbose_name=field_name))
    
    if not fields_list:
      self.response.out.write('No fields provided!')
      return
    
    FieldSet.create(self.dataset.key(), name, *fields_list)
    
    msg = urllib.urlencode({'flash' : 'Field Set Created'})
    self.redirect("/fieldsets?" + msg)
